import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, In } from 'typeorm';
import * as dayjs from 'dayjs';
import { AuthService } from '@auth/auth.service';
import { AlbumEntity } from './entity/album.entity';
import { AlbumListEntity } from './entity/album.list.entity';
import { CreateAlbumDto, SavePhoneDto, UpdatePhoneDto } from './dto/index';

@Injectable()
export class AlbumService {
  constructor(
    private readonly authService: AuthService,
    @InjectRepository(AlbumEntity)
    private readonly albumRepository: Repository<AlbumEntity>,
    @InjectRepository(AlbumListEntity)
    private readonly albumListRepository: Repository<AlbumListEntity>,
  ) {}

  /**
   * 创建相册
   */
  async createAlbum(token: string, body: CreateAlbumDto) {
    const tokenResult = await this.authService.getTokenUser(token);
    await this.albumRepository.save({
      uid: tokenResult.userId,
      name: body.name,
      imgUrl: body.imgUrl,
      desc: body.desc,
    });
    return { code: 200, msg: '创建相册成功' };
  }

  /**
   * 删除相册
   */
  async deleteAlbum(token: string, body: { id: number }) {
    const tokenResult = await this.authService.getTokenUser(token);
    await this.albumRepository.createQueryBuilder().delete().where({ id: body.id, uid: tokenResult.userId }).execute();
    const albumListData = await this.albumListRepository.find({
      where: { uid: tokenResult.userId, albumId: body.id },
    });
    const formatData = albumListData.map((item) => {
      return {
        uid: item.uid,
        albumId: body.id,
      };
    });
    await this.albumListRepository.createQueryBuilder().delete().where(formatData).execute();
    return { code: 200, msg: '删除相册' };
  }

  /**
   * 修改相册
   */
  async updateAlbum(token: string, body: CreateAlbumDto) {
    const tokenResult = await this.authService.getTokenUser(token);
    const result = await this.albumRepository
      .createQueryBuilder()
      .update()
      .set({
        name: body.name,
        imgUrl: body.imgUrl,
        desc: body.desc,
        endTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      })
      .where({ uid: tokenResult.userId, id: body.id })
      .execute();
    return { code: 200, msg: '修改相册成功', data: result };
  }

  /**
   * 相册列表
   */
  async albumList(token: string) {
    const tokenResult = await this.authService.getTokenUser(token);
    const result = await this.albumRepository.find({ where: { uid: tokenResult.userId }, order: { id: 'DESC' } });
    return { code: 200, msg: '获取相册列表', data: result };
  }

  /**
   * 获取 相册详情
   */
  async albumDetails(token: string, query: { id: number }) {
    const tokenResult = await this.authService.getTokenUser(token);
    const result = await this.albumRepository.findOne({
      where: { id: query.id, uid: tokenResult.userId },
      order: { id: 'DESC' },
    });
    const count = await this.albumListRepository
      .createQueryBuilder()
      .where({ albumId: query.id, uid: tokenResult.userId })
      .getCount();
    console.log('count', count);
    return { code: 200, msg: '相册详情', data: { ...result, count } };
  }

  /**
   * 相册 保存照片
   */
  async savePhone(token: string, body: SavePhoneDto) {
    const tokenResult = await this.authService.getTokenUser(token);
    const imgUrlArr = body.imgUrl.split(',').map((item) => {
      return {
        uid: tokenResult.userId,
        albumId: body.id,
        imgUrl: item,
      };
    });
    console.log('保存照片', imgUrlArr);
    await this.albumListRepository.save(imgUrlArr);
    return { code: 200, msg: '保存照片成功' };
  }

  /**
   * 相册 删除照片
   */
  async deletePhone(token: string, body: { id: number }) {
    const tokenResult = await this.authService.getTokenUser(token);
    await this.albumListRepository
      .createQueryBuilder()
      .delete()
      .where({ id: body.id, uid: tokenResult.userId })
      .execute();
    return { code: 200, msg: '删除成功' };
  }

  /**
   * 相册 批量删除照片
   */
  async batchDeletePhone(token: string, body: { id: string }) {
    const tokenResult = await this.authService.getTokenUser(token);
    const idsArr = body.id.split(',');
    const formatData = idsArr.map((item) => {
      return {
        id: item,
        uid: tokenResult.userId,
      };
    });
    console.log('formatData', formatData);
    await this.albumListRepository.createQueryBuilder().delete().where(formatData).execute();
    return { code: 200, msg: '删除成功' };
  }

  /**
   * 相册 修改照片
   */
  async updatePhone(token: string, body: UpdatePhoneDto) {
    const tokenResult = await this.authService.getTokenUser(token);
    console.log('update', body);
    await this.albumListRepository
      .createQueryBuilder()
      .update()
      .set({
        name: body.name,
        imgUrl: body.imgUrl,
        desc: body.desc,
        address: body.address,
        endTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      })
      .where({ id: body.id, uid: tokenResult.userId })
      .execute();
    return { code: 200, msg: '修改照片成功' };
  }

  /**
   * 相册 获取照片列表
   */
  async phoneList(token: string, query: { id: number }) {
    const result = await this.albumListRepository.find({ where: { albumId: query.id }, order: { id: 'DESC' } });
    return { code: 200, msg: '获取照片列表', data: result };
  }
}
